package com.henu.main.executors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.henu.main.entities.Metric;
import com.henu.main.util.MetricsUtil;
import com.henu.main.util.TimeUtil;
import com.henu.main.util.WebUtil;

import java.util.HashMap;
import java.util.Set;

public class LastContactExecutor implements Runnable {


    private String hostname;
    private String cluster;

    public LastContactExecutor(String hostname, String cluster) {
        this.hostname = hostname;
        this.cluster = cluster;
    }

    @Override
    public void run() {
        String html = WebUtil.get("http://" + hostname + ":9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo");
        JSONArray array = (JSONArray) JSON.parseObject(html, HashMap.class).get("beans");
        HashMap resultMap = JSON.parseObject(array.get(0).toString(), HashMap.class);
        String liveNodesJSON = resultMap.get("LiveNodes").toString();
        HashMap liveNodesMap = JSON.parseObject(liveNodesJSON, HashMap.class);
        Set keys = liveNodesMap.keySet();
        for (Object key : keys) {
            HashMap valueMap = JSON.parseObject(liveNodesMap.get(key.toString()).toString(), HashMap.class);
            Double lastContact = Double.parseDouble(valueMap.get("lastContact").toString());
            Metric metric1 = new Metric();
            metric1.setCluster(cluster);
            metric1.setServiceName("HDFS" + ":" + hostname);
            metric1.setMetricName("LastContact");
            metric1.setHostname(key.toString().split(":")[0]);
            metric1.setTimestamp(TimeUtil.getNowTimestamp());
            metric1.setValue(lastContact);
            try {
                MetricsUtil.queue.put(metric1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }

}
